package com.bwie.coupon.mq;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.bwie.common.doamin.model.UserCoupon;
import com.bwie.common.doamin.vo.CouponSimpleVO;
import com.bwie.common.exceptions.BizException;
import com.bwie.coupon.mapper.CouponMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * 异步发送优惠券
 *
 * @author <a href="mailto:2943147140@qq.com">刘洋朔</a>
 * @version 1.0
 * @description: 异步发送优惠券
 * @date 2025/9/9 11:51
 */
@Log4j2
@Component
public class SendCouponMq {
    //自动给用户发送满10.01元减10元的新人优惠券
    private final static Long couponId = 1L;

    @Autowired
    private CouponMapper couponMapper;
    /**
     * 中间件发送优惠券
     * @param userId
     */
    @KafkaListener(topics = "sendCoupon")
    public void sendCoupon(Long userId){
        //注册成功系统使用MQ异步通知优惠券系统，自动给用户发送满10.01元减10元的新人优惠券（2分）
        //获取优惠券的信息
        CouponSimpleVO couponSimpleVO = couponMapper.selCouponInfoSimple(couponId);
        if(ObjectUtils.isEmpty(couponSimpleVO)){
            log.info("满10.01元减10元的新人优惠券数据有误,请及时修复");
            throw new BizException("优惠券正在放送,请稍后");
        }
        //算取过期时间
        DateTime dateTime = DateUtil.offsetDay(new Date(), couponSimpleVO.getValidDays());
        //给用户发放优惠券
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setCouponId(couponId);
        userCoupon.setUserId(userId);
        userCoupon.setUseType(couponSimpleVO.getApplicableCategory());
        userCoupon.setExpirationDate(dateTime);
        couponMapper.sendCouponToUser(userCoupon);
        //优惠券数量变更
        couponMapper.updateCouponDiffNum(couponId);
    }
}
